package com.sunjob.mroimg.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.sunjob.common.domain.img.SysImg;
import com.sunjob.common.mroAnno.ControllerLog;
import com.sunjob.common.mroAnno.LogModuleType;
import com.sunjob.common.result.Result;
import com.sunjob.common.util.PageHelper;
import com.sunjob.mroimg.config.ImgConfiguration;
import com.sunjob.mroimg.service.ImgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-09 8:37
 * 图片服务器控制器类
 */
@RestController
@CrossOrigin
@Api(value = "图片上传api")
public class ImgController {


    @Autowired
    ImgConfiguration imgConfiguration;
    @Autowired
    ImgService imgService;

    /**
     * 该接口供微服务调用 不提供给前端调用
     * 传入图片相对地址格式为 模块地址/图片名称.后缀名
     * 例如 loginServer/xxx.png
     *
     * @param sysImg 传入图片字节数组 返回图片映射地址 图片的大小 图片的id 和其他基本信息
     * @return
     */
    @ApiOperation(value = "推送图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysImg", value = "图片实体")
    })
    @PostMapping("/pushImg")
    public Result<SysImg> pushImg(@RequestBody SysImg sysImg) {
        return handleCommon(sysImg);
    }

    @ApiOperation(value = "条件获取图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "img", value = "图片实体")
    })
    @PostMapping("/pullImgBy")
    @SaCheckPermission("system:img:query")
    public Result<List<SysImg>> pullImgBy(@RequestBody SysImg img) {
        List<SysImg> sysImgs = imgService.pullImgBy(img);
        String prefix = imgService.getPrefix();
        sysImgs.forEach(e -> e.setAbImgUrl(prefix + e.getImgUrl()));
        return Result.ok(sysImgs, "查询图片信息成功");
    }

    @ApiOperation(value = "获取所有图片信息")
    @SaCheckPermission("system:img:query")
    @GetMapping("/queryAllImg")
    public Result<List<SysImg>> getAllImg() {
        List<SysImg> sysImgs = imgService.queryAllImg();
        String prefix = imgService.getPrefix();
        sysImgs.forEach(e -> e.setAbImgUrl(prefix + e.getImgUrl()));
        return Result.ok(sysImgs, "查询所有图片信息成功");
    }

    @ApiOperation(value = "分页获取图片信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startPage", value = "起始页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数"),
            @ApiImplicitParam(name = "pageNum", value = "总页数")
    })
    @SaCheckPermission("system:img:query")
    @GetMapping("/queryImgByPage/{startPage}/{pageSize}/{pageNum}")
    public Result<List<List<SysImg>>> getImgByPage(@PathVariable("startPage") Integer startPage,
                                                   @PathVariable("pageSize") Integer pageSize,
                                                   @PathVariable("pageNum") Integer pageNum
    ) {
        List<SysImg> sysImgs = imgService.queryAllImg();
        String prefix = imgService.getPrefix();
        // 动态添加前缀
        sysImgs.forEach(e -> e.setAbImgUrl(prefix + e.getImgUrl()));
        PageHelper<SysImg> pageHelper = new PageHelper<>(sysImgs);
        List<List<SysImg>> pageInfo = pageHelper.getPageInfo(startPage, pageSize, pageNum);
        return Result.ok(pageInfo, "查询图片信息成功");
    }

   // @SaCheckPermission("system:img:query")
    @GetMapping("/getImgById/{imgId}")
    @ApiOperation(value = "通过id获得图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgId", value = "图片编号")
    })
    public Result<SysImg> getImgById(@PathVariable("imgId") Long imgId) {
        SysImg imgById = imgService.getImgById(imgId);
        if (imgById != null) {
            // 动态添加url前缀
            imgById.setAbImgUrl(imgService.getPrefix() + imgById.getImgUrl());
        }
        return Result.ok(imgById, "查询图片信息成功");
    }
    /**
     * 上传敏感图片
     * 传入图片相对地址格式为 图片名称.后缀名
     * 例如 xxx.png
     *
     * @param sysImg
     * @return
     */
    @ApiOperation(value = "推送敏感图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysImg", value = "图片实体")
    })
    @PostMapping("/pushImgPrivate")
    public Result<SysImg> pushImgPrivate(@RequestBody SysImg sysImg) {
        return handleCommon(sysImg);
    }

    private boolean verifyUrl(String url) {
        boolean res = false;
        for (int i = 0; i < imgConfiguration.getSuffix().size(); i++) {
            if (url.endsWith(imgConfiguration.getSuffix().get(i))) {
                res = true;
            }
        }
        return res;
    }

    private Result<SysImg> handleCommon(SysImg sysImg) {
        if (sysImg.getData() == null || sysImg.getData().length == 0) {
            return Result.fail("图片上传失败");
        }
        String url = sysImg.getImgUrl();
        if (url == null) {
            return Result.fail("url不能为空");
        }
        if (!verifyUrl(url)) {
            return Result.fail("不支持的图片格式");
        }
        sysImg = imgService.saveImg(sysImg);
        if (sysImg == null) {
            return Result.fail("图片上传失败");
        }
            // 动态添加url前缀
        sysImg.setAbImgUrl(imgService.getPrefix() + sysImg.getImgUrl());
        return Result.ok(sysImg, "图片上传成功");
    }

}
